package easy;

import java.util.HashMap;
import java.util.Map;

public class numIdenticalPairs {

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 1, 1, 3};
        System.out.println(ans(nums));
        System.out.println(violence(nums));
    }

    /**
     * 暴力解决,嵌套循环
     * 时间复杂度O(n²)
     * 空间复杂度O(1)
     * @param nums
     * @return
     */
    public static int violence(int[] nums) {
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i+1; j < nums.length; j++) {
                if (nums[i] == nums[j]) {
                    sum += 1;
                }
            }
        }
        return sum;
    }

    /**
     * 先使用map保存各数在数组中的总量，再遍历map按计算等差数列之和即可
     * 时间复杂度O(n)
     * 空间复杂度O(n)
     * @param nums
     * @return
     */
    public static int ans(int[] nums) {
        Map<Integer, Integer> m = new HashMap<Integer, Integer>();
        for (int num : nums) {
            m.put(num, m.getOrDefault(num, 0) + 1);
        }

        int sum = 0;
        for (Map.Entry<Integer, Integer> entry : m.entrySet()) {
            int v = entry.getValue();
            sum += v * (v - 1) / 2;
        }
        return sum;
    }
}
